layui.config({base: '' + '/lib/modules/'});
layui.use(['notice'], function () {
    // 初始化配置，同一样式只需要配置一次，非必须初始化，有默认配置
    layui.notice.options = {
        closeButton: true,//显示关闭按钮
        debug: false,//启用debug
        positionClass: 'toast-top-center',//弹出的位置, toast-top-center toast-top-right
        showDuration: '300',//显示的时间
        hideDuration: '1000',//消失的时间
        timeOut: '2000',//停留的时间
        extendedTimeOut: '1000',//控制时间
        showEasing: 'swing',//显示时的动画缓冲方式
        hideEasing: 'linear',//消失时的动画缓冲方式
        onclick: null // 点击关闭回调
    };
});

var dateQuickSelect = (function () {
    function dateQuickSelect() {
    };
    this.lastDays = function (eleId, daysAgo, includeToday) {
        var date1 = new Date();
        var date2 = new Date();
        date1.setDate(date1.getDate() - daysAgo);
        date1.setHours(0, 0, 0, 0);
        if (includeToday) {
            date2.setDate(date2.getDate() + 1);
        }
        date2.setHours(0, 0, 0, 0);
        layui.$('#' + eleId).val(layui.util.toDateString(date1, "yyyy-MM-dd HH:mm:ss") + ' ~ ' + layui.util.toDateString(date2, "yyyy-MM-dd HH:mm:ss"));
        layui.$('body').trigger('click');
    };
    dateQuickSelect.today = function (eleId) {
        lastDays(eleId, 0, true);
    };
    dateQuickSelect.yesterday = function (eleId) {
        lastDays(eleId, 1, false);
    };
    dateQuickSelect.last_days_3 = function (eleId) {
        lastDays(eleId, 3, true);
    };
    dateQuickSelect.last_days_7 = function (eleId) {
        lastDays(eleId, 7, true);
    };
    return dateQuickSelect;
}());

// 转换试题内容中的上传图片
var convertQuesContentImg = function (content) {
    if (content === '') return '';
    var imgUri = 'http://static.zujuan.xkw.com/Upload';
    if (content.indexOf(imgUri) < 0) {
        return content.replace(new RegExp("src=\"Upload/", "gm"), "src=\"" + imgUri + "/");
    }
    return content;
};

layui.$(function(){
    var element = layui.element; //加载element模块

    /* 侧边栏开关 */
    $(".side-toggle").on("click", function (e) {
        e.preventDefault();
        var to = $(".layui-layout-admin");
        to.toggleClass("layui-side-shrink");
        to.attr("toggle") === 'on' ? to.attr("toggle", "off") : to.attr("toggle", "on");
    });
    $(".layui-side").on("click", function () {
        var to = $(".layui-layout-admin");
        if (to.attr("toggle") === 'on') {
            to.attr("toggle", "off");
            to.removeClass("layui-side-shrink");
        }
    });

    /* 最大化窗口 */
    $(".zjgl-screen-full").on("click", function (e) {
        e.preventDefault();
        if (!$(this).hasClass("full-on")) {
            var docElm = document.documentElement;
            var full = docElm.requestFullScreen || docElm.webkitRequestFullScreen ||
                docElm.mozRequestFullScreen || docElm.msRequestFullscreen;
            "undefined" !== typeof full && full && full.call(docElm);
        } else {
            document.exitFullscreen ? document.exitFullscreen()
                : document.mozCancelFullScreen ? document.mozCancelFullScreen()
                : document.webkitCancelFullScreen ? document.webkitCancelFullScreen()
                    : document.msExitFullscreen && document.msExitFullscreen()
        }
        $(this).toggleClass("full-on");
    });
    
    /* 新建或切换标签栏 */
    var tabs = function (url) {
        if (url != undefined && url != '#' && url.length> 0) {
            url = url.split(';')[0];
            url = url.replace("/wanwei","");
            var item = $('[lay-url="/wanwei' + url + '"]');
            if(!url.includes('/dashboard')){
                var bootLay = $('[lay-id="/dashboard"]');
                if (bootLay.length === 0) {
                    var title = '首页';
                    var iframeUrl = (window.location.pathname + '/dashboard').replace('//','/');
                    element.tabAdd('iframe-tabs', {
                        title: title
                        , content: '<iframe src="' + iframeUrl + '" frameborder="0" class="layui-layout-iframe"></iframe>'
                        , id: '/dashboard'
                    });
                }
            }

            var bootLay = $('[lay-id="' + url + '"]');
            if (bootLay.length === 0) {
                var title = item.attr("lay-icon") === 'true' ? item.html()
                    : item.children(".layui-nav-title").text();
                var iframeUrl = (window.location.pathname + url).replace('//','/');
                element.tabAdd('iframe-tabs', {
                    title: title
                    , content: '<iframe src="' + iframeUrl + '" frameborder="0" class="layui-layout-iframe"></iframe>'
                    , id: url
                });
            }
            element.tabChange('iframe-tabs', url);
        }
    };

    /* 监听水平导航栏事件，实现侧边栏的切换 */
    // element.on("nav(layui-nav-level)", function ($this) {
    //     var id = $this.parent().data('menu');
    //     //console.log($this);
    //     $this.parent().addClass('layui-head-nav-selected');
    //     $this.parent().siblings().removeClass('layui-head-nav-selected');
    //     // left
    //     $(".layui-nav.layui-nav-tree").addClass('layui-hide');
    //     $(".layui-nav.layui-nav-tree.layui-this.layui-hide").removeClass('layui-this');
    //     $("#" + id).removeClass('layui-hide');
    //     $("#" + id).addClass('layui-this');
    // });

    // /* 监听导航栏事件，实现标签页的切换 */
    // element.on("nav(layui-nav-side)", function ($this) {
    //     var url = $this.attr('lay-url');
    //     tabs(url);
    // });
    //
    // /* 监听标签栏事件，实现导航栏高亮显示 */
    // element.on("tab(iframe-tabs)", function () {
    //     var layId = $(this).attr("lay-id");
    //     $(".layui-side .layui-this").removeClass("layui-this");
    //     $('[lay-url="' + layId + '"]').parent().addClass("layui-this");
    //     // 改变地址hash值
    //     location.hash = this.getAttribute('lay-id');
    // });
    
    /* 监听hash来切换选项卡*/
    window.onhashchange = function (e) {
        var url = location.hash.replace(/^#/, '');
        var index = $(".layui-layout-admin .layui-side .layui-nav-item")[0];
        $(index).children("a").attr("lay-icon", "true");
        if (url === "" || url === undefined) {
            url = $(index).children("[lay-url]").attr("lay-url");
        }
        tabs(url);
    };
    window.onhashchange();
    
    /* 初始化时展开子菜单 */
    $("dd.layui-this").parents(".layui-nav-child").parent()
        .addClass("layui-nav-itemed");
    
    /* 刷新iframe页面 */
    $(".page-refresh-btn").click(function () {
        location.reload();
    });
});

var utils = (function () {

    function utils() { }

    /**
     * 获取URL中传递的GET参数
     * @param {*} name 参数名字
     */
    utils.getQueryString = function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1]);
    };

    /**
     * 得到UUID字符
     * @param {*} len 字符长度
     * @param {*} radix 进制
     */
    utils.newUUID = function (len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    };

    utils.setCookie = function(name, value, hours) {
        var exp = new Date();
        exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
        document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString() + ";path=/";
    };

    utils.getCookie = function(name) {
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null) {
            return decodeURIComponent(arr[2]);
        }
        else {
            return null; //unescope
        }
    };

    utils.delCookie = function (name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = this.Get(name);
        if (cval != null) { document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/"; }
    };

    /**
     * 测试方法
     */
    utils.foo = function () {
        console.log('foo run...');
    };

    return utils;
}());

window.App = (function () {
    var cookie_bankId = "bank_id";
    return {
        getCookieBankId: function () {
            var bankid = utils.getCookie(cookie_bankId);
            if (bankid === "" || bankid == null) {
                bankid = 11;
            }
            return bankid;
        },
        setCookieBankId: function (bankId) {
            utils.setCookie(cookie_bankId, bankId, 24*365)
        },
        delCookieBankId: function () {
            utils.delCookie(cookie_bankId);
        }
    };
})();